package com.alphathink.deliveryassist.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.AlphaThink.DeliveryAssist.R;
import com.alphathink.deliveryassist.adapter.MessageListViewAdapter;
import com.alphathink.deliveryassist.eneity.Contact;
import com.alphathink.deliveryassist.eneity.ContactBean;
import com.alphathink.deliveryassist.util.KeyUtil;
import com.google.gson.Gson;
import com.zxing.activity.CaptureActivity;

/***
 * 短信模式,扫一扫获取用户信息,
 * 
 * @author click
 * 
 */
public class MessageFragment extends Fragment {
	/** 短信接受的监听类 */
	private SMSSendResultReceiver mSMSReceiver, mSMSReceiver01;
	/** 过滤短信 */
	private IntentFilter mSMSResultFilter = new IntentFilter();
	/** 短信的发送动作 */
	private static final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
	/** 短信接受的动作 */
	private static final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
	String str = null;
	private static final String TAG = "PhoneModelActivity";
	/** 扫描按钮，点击进入扫描二维码 */
	private ImageButton imageButtonScan = null;

	private ListView listView = null;
	/** 创建一个快件信息的对象 */
	private ContactBean bean = null;
	private ArrayList<ContactBean> beanList = new ArrayList<ContactBean>();

	/** listView适配 */
	private MessageListViewAdapter messageListViewAdapter = null;
	private ListViewOnItemClickListener listViewOnItemClick = null;

	private Button buttonPost = null;
	private View view = null;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		view = inflater.inflate(R.layout.activity_message_fragment_model,
				container, false);

		initView();
		initPostView();
		return view;
	}

	/**
	 * 初始化布局view
	 */
	private void initView() {

		listView = (ListView) view
				.findViewById(R.id.activity_message_model_ListViewUser);

		messageListViewAdapter = new MessageListViewAdapter(beanList,
				getActivity());
		listView.setAdapter(messageListViewAdapter);

		imageButtonScan = (ImageButton) view
				.findViewById(R.id.activity_message_model_ImageButtonScan);
		imageButtonScan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d(TAG, "进入扫描模式获取用户信息");
				Intent intent = new Intent();
				intent.setClass(getActivity(), CaptureActivity.class);
				startActivityForResult(intent, 0);
			}

		});

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.v(TAG, "扫描返回数据");
		if (resultCode == CaptureActivity.CAP_RESULT) {
			String info = data.getExtras().getString("result");
			System.out.println(info
					+ "MessageModelActivity107----------------------------");
			bean = new ContactBean();
			Contact contact = new Contact();
			Gson gson = new Gson();
			Log.v(TAG, "获取数据:" + info);
			String mTmp = KeyUtil.decrypt(info);
			Log.v(TAG, "获取数据:" + mTmp);
			try {
				contact = gson.fromJson(mTmp, Contact.class);
				bean = contact.getBeans().get(0);
			} catch (Exception e) {
				Log.e(TAG, e.toString());
			}
			if (bean.getContactNum() == null
					&& bean.getContactAddress() == null
					&& bean.getContactName() == null) {

				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setMessage("信息为空，请重新扫描。").setCancelable(true);
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			// 该处之前没有初始化
			else {
				beanList.add(bean);
				ListAsyncTask listAsyncTask = new ListAsyncTask();
				listAsyncTask.execute();
			}
		}

	}

	class ListAsyncTask extends AsyncTask<Integer, Integer, String> {

		@Override
		protected String doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			messageListViewAdapter.setListData(beanList);
			messageListViewAdapter.notifyDataSetChanged();

			// listView.setOnItemClickListener(new OnItemClickListener() {
			//
			// @Override
			// public void onItemClick(AdapterView<?> parent, View view,
			// int position, long id) {
			// // TODO Auto-generated method stub
			// Intent intent01 = new Intent();
			//
			// intent01.setClass(MessageModelActivity.this,
			// ContactInfoActivity.class);
			// intent01.putExtra("contact", beanList.get(position));
			// Log.d(TAG, String.valueOf(beanList.get(position))
			// + "------第几个");
			// startActivity(intent01);
			// }
			// });
		}
	}

	/* *
	 * 实现放送功能
	 */
	void initPostView() {

		buttonPost = (Button) view.findViewById(R.id.BTN_call_phoneModel);
		buttonPost.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final SharedPreferences share = getActivity()
						.getApplicationContext().getSharedPreferences("model",
								0x0000);

				String modelName01 = share.getString("modelName01", "模块一");
				String modelName02 = share.getString("modelName02", "模块二");
				String modelName03 = share.getString("modelName03", "模块三");
				String modelName04 = share.getString("modelName04", "模块四");
				final CharSequence[] items = { modelName01, modelName02,
						modelName03, modelName04 };
				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				Log.e(TAG, "-----------");
				builder.setTitle("选择短信模板！");
				Log.e(TAG, "11111111111111");
				System.out.println("str-=-=-=-=-=" + str + "item-=-=-==+"
						+ items);
				builder.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int item) {
						// Toast.makeText(getApplicationContext(), items[item],
						// Toast.LENGTH_SHORT).show();
						if (item == 0) {
							str = share.getString("modelMessage01", null);
						} else if (item == 1) {
							str = share.getString("modelMessage02", null);
						} else if (item == 2) {
							str = share.getString("modelMessage03", null);
						} else if (item == 3) {
							str = share.getString("modelMessage04", null);
						}

						SmsManager smsManager = SmsManager.getDefault();
						try {
							Log.e(TAG, String.valueOf(beanList.size()));
							for (int i = 1; i <= beanList.size(); i++) {
								Log.e(TAG,
										"------------------------------------");
								Intent itSent = new Intent(SENT_SMS_ACTION);
								Intent itDeliver = new Intent(
										DELIVERED_SMS_ACTION);
								itSent.putExtra("KEY_PHONENUM",
										beanList.get(i - 1).getContactName());
								/** 短信发送的时候的pendingIntent的状态 */
								PendingIntent mSendPI = PendingIntent
										.getBroadcast(getActivity()
												.getApplication(), i - 1,
												itSent,
												PendingIntent.FLAG_ONE_SHOT);
								/** 短信送达之后的pendingIntent的状态 */
								PendingIntent mDeliverPI = PendingIntent
										.getBroadcast(getActivity()
												.getApplication(), item,
												itDeliver,
												PendingIntent.FLAG_ONE_SHOT);
								smsManager.sendTextMessage(beanList.get(i - 1)
										.getContactNum(), null, str, mSendPI,
										mDeliverPI);

							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});
				AlertDialog alert = builder.create();
				alert.show();

			}
		});
	}

	class SMSSendResultReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String mUserName = intent.getStringExtra("KEY_PHONENUM");
			// TODO Auto-generated method stub
			switch (getResultCode()) {
			case Activity.RESULT_OK:
				System.out
						.println("Send Message to " + "发往" + mUserName + "成功");
				if (mUserName != null) {
					Toast.makeText(getActivity().getApplication(),
							"发往" + mUserName + "成功", Toast.LENGTH_SHORT).show();
					break;
				}
				break;
			case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
				break;
			case SmsManager.RESULT_ERROR_RADIO_OFF:
				break;
			case SmsManager.RESULT_ERROR_NULL_PDU:
				break;
			default:
				System.err.println("Send Message to " + "发往" + mUserName
						+ " fail!");
				Toast.makeText(getActivity().getApplication(),
						"发往" + mUserName + "失败", Toast.LENGTH_SHORT).show();
				// 此处还要对发送失败的时候做处理
				break;
			}
		}
	}

	@Override
	public void onResume() {
		/** 自定义一个intentFilter为SMS_SENT_ACTION receiver */
		IntentFilter mFilter01;
		mFilter01 = new IntentFilter(SENT_SMS_ACTION);
		mSMSReceiver = new SMSSendResultReceiver();
		getActivity().registerReceiver(mSMSReceiver, mFilter01);

		/** 为短信接受状态接受 设置一个reciver */
		mFilter01 = new IntentFilter(DELIVERED_SMS_ACTION);
		mSMSReceiver01 = new SMSSendResultReceiver();
		getActivity().registerReceiver(mSMSReceiver01, mFilter01);

		super.onResume();
	}

	@Override
	public void onPause() {
		/** 取消自定义的reciver */
		getActivity().unregisterReceiver(mSMSReceiver);
		getActivity().unregisterReceiver(mSMSReceiver01);
		super.onPause();
	}

	/*
	 * 
	 * ListView子类监听事件
	 */
	class ListViewOnItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

		}

	}
}
